import os
import time
import traceback
from collections import OrderedDict
from urllib import parse

import requests
from PyQt5.QtCore import QThreadPool, QRunnable
from bs4 import BeautifulSoup


def get_num(mh_name, page):
    # 此方法适用于 全局代理方式代理访问
    proxy_url = "http://127.0.0.1:7890"  # 为本机代理端口及ip
    os.environ['HTTP_PROXY'] = proxy_url
    os.environ['HTTPS_PROXY'] = proxy_url

    str_val = parse.quote(mh_name)
    headers = {
        'Referer': f'https://missav789.com/search/{str_val}',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/126.0.0.0 Mobile Safari/537.36',
        'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        'sec-ch-ua-mobile': '?1',
        'sec-ch-ua-platform': '"Android"',
    }

    response = requests.get(f'https://missav789.com/cn/search/{str_val}?page={page}', headers=headers)

    print(response.status_code)
    soup = BeautifulSoup(response.text, 'html.parser')
    a_items = (
        soup.find_all("a", class_="text-secondary group-hover:text-primary")
    )
    name_list = []
    for item in a_items:
        name_list.append(item.get('href'))
        print(item.get('href'))
    return name_list


def get_video(http):
    # 此方法适用于 全局代理方式代理访问
    proxy_url = "http://127.0.0.1:7890"  # 为本机代理端口及ip
    os.environ['HTTP_PROXY'] = proxy_url
    os.environ['HTTPS_PROXY'] = proxy_url

    cookies = {
        '_ga': 'GA1.1.1644562024.1727666023',
        'user_uuid': '70a43435-0ac2-4461-9741-25ed6a41f4da',
        'search_history': '[%22%25E5%2593%2588%25E5%2593%2588%22]',
        '_ga_Z3V6T9VBM6': 'GS1.1.1727674982.2.1.1727674984.0.0.0',
        'XSRF-TOKEN': 'eyJpdiI6IlBPY0J1YTNtWWxXV2JsbUR0aVJSTVE9PSIsInZhbHVlIjoiOTVSVE5kcm1aLy9YbVBvUzhTQ0hoY21IWEtTMTFmV0JkY1lTUXNwR0pGaHExb2lnRjRFNUF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k4QVVjV0dpaW1OMzY1bm51Q0NZdWtsMlE2QlZrQXF0elpnWVdsVHRmVDVYUGRnNmEzSkw1REc2bmJFVzhFVmxIYXBBU0tzcFI0OVlxbGRIWlZONGtLR3RZZ3dYa0NjeWVXVk1KeWg1aVJDWEs5OGdmdz09IiwibWFjIjoiMzJmNTU3YWIyMDM5YTViOGZlMzkyNGQxNzhlMDliNTgxNmE4MjlmYTE0YTcyMDNmYWM0OWU1MDI0MzZjNWMyNyIsInRhZyI6IiJ9',
        'cf_clearance': 'r3QhGL7T2Yo_B_WQ5zQoOP2eDScHdF.4.SUZVL1WRLQ-1727674949-1.2.1.1-JK00.GQa1gA5UByu.kW3EZ0MSsHji6rKZuk058p9Cjru_Wo3uPT_d1NOFDovwNYtEebloBpMdEa6uh2aUi88StxIyvqyftD.xpBjS2ddDKG17IFzMEDY7qurOb2y0hv4o4sdtISx3SbcdVCxfFvRfb768jgJoOs3GusZD3ZlRyYDTxWlBIS5U1cgdo2Hw3aJdksTqlHBHvHR8HQqXCPvLHGTual8mM4mbXspP96_n3g7bGAkF4LAI4oDO1mTvCewUIkiw4njg.vi.QYssWlHLoTI_6Htt7v4Wx3nEw8_3AxL_46gQaH2.gMm79_p0EtD2.YyXHLMalxOPewi_W5wVcPV9Q6dM1x0wtRIqyqR1gKeR3Axm1maVCPCr_krwzkZh0LIPfPbe9d9re1orMxwV0YRUcqcXaWJWeL0epCBBMo',
    }

    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,'
                  'application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
        'cache-control': 'max-age=0',
        'if-modified-since': 'Mon, 30 Sep 2024 05:29:39 GMT',
        'priority': 'u=0, i',
        'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        'sec-ch-ua-mobile': '?1',
        'sec-ch-ua-platform': '"Android"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'none',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/126.0.0.0 Mobile Safari/537.36',
    }

    response = requests.get(f'{http}', cookies=cookies, headers=headers)
    print(response.status_code)
    soup = BeautifulSoup(response.text, 'html.parser')
    description = soup.find('meta', attrs={'name': 'description'}).get("content")
    title = soup.find('meta', attrs={'property': 'og:title'}).get("content")
    print(description)
    print(title)

def download_video(url, fileName, ix, idx):
    """
    下载图片到本地
    :param idx: 下标
    :param ix: 章节
    :param fileName: 存放文件夹
    :param url: 图片的URL
    """
    try:
        # 发送GET请求获取图片
        response = requests.get(url, stream=True)
        mkdirFile(fileName)
        save_path = f"{fileName}/{ix}_{int(time.time() * 10)}_{idx}.jpg"
        # 检查请求是否成功
        if response.status_code == 200:
            # 打开文件以二进制写模式
            with open(save_path, 'wb') as file:
                # 迭代响应内容，并写入文件
                for chunk in response:
                    file.write(chunk)

            # 如果你安装了Pillow库，可以打开图片以验证下载是否成功
            # img = Image.open(save_path)
            # img.show()

            print(f"Image downloaded successfully to {save_path}")
        else:
            print(f"Failed to download image from {url}. Status code: {response.status_code}")

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")


def mkdirFile(fileName):
    # 获取当前目录
    current_directory = os.getcwd()
    # 指定要创建的目录路径
    directory = f"{current_directory}/{fileName}"
    # 使用 os.makedirs 创建目录
    # 如果目录已存在，可以设置 exist_ok=True 来避免引发异常
    try:
        os.makedirs(directory, exist_ok=True)
    except OSError as e:
        print(f"创建目录时发生错误: {e}")


class TaskRunnable(QRunnable):
    def __init__(self, data):
        super(TaskRunnable, self).__init__()
        self.data = data

    def run(self):
        # 这里执行你的任务，处理 self.data
        if self.data is None:
            return
        nums_list, namedesc_list = get_num(self.data)
        print(nums_list)
        for ix, num in enumerate(nums_list):
            pic_data = get_pic(num)
            for index, a in enumerate(pic_data):
                download_image(a, namedesc_list[ix], str(ix), index)


if __name__ == '__main__':
    # 多线程 线程池
    # threadpool = QThreadPool()
    # threadpool.setMaxThreadCount(20)
    result = get_num("3d", page=1)
    for item in result:
        get_video(item)
    # list_total = ["化妆"
    #               ]
    # for value in list_total:
    #     print(f"打印头：{value}")
    #     runnable = TaskRunnable(value)
    #     threadpool.start(runnable)


